package com.example.design;

/**
 * 简单工厂
 * @author xiaohf
 * @createTime 2021/8/25 20:33
 **/
public class SimpleFactory {
    public static void main(String[] args) throws Exception {
        Operation operation = OperationFactory.createOperation("*");
        operation.number1 = 5;
        operation.number2 = 2;
        double result = operation.getResult();
        System.out.println(result);
    }
}

/**
 * 公共运算类
 * @author xiaohf
 * @createTime 2021/8/25 20:53
 **/
class Operation{
    public double number1;
    public double number2;

    public double getResult() throws Exception {
        return 0;
    }

}
/**
 * 加法操作
 * @author xiaohf
 * @createTime 2021/8/25 20:40
 **/
class OperationAdd extends Operation{
    @Override
    public double getResult() {
        return number1 + number2;
    }
}

/**
 * 减法操作
 * @author xiaohf
 * @createTime 2021/8/25 20:40
 **/
class OperationSub extends Operation{
    @Override
    public double getResult() {
        return number1 - number2;
    }
}


/**
 * 乘法操作 multiplication method
 * @author xiaohf
 * @createTime 2021/8/25 20:40
 **/
class OperationMul extends Operation{
    @Override
    public double getResult() {
        return number1 * number2;
    }
}


/**
 * 除法操作 division method
 * @author xiaohf
 * @createTime 2021/8/25 20:40
 **/
class OperationDiv extends Operation{
    @Override
    public double getResult() throws Exception {
        if (number2 == 0) {
            throw new Exception("除数不能为0");
        }
        return number1 / number2;
    }
}
/**
 * 计算工厂类
 * @author xiaohf
 * @createTime 2021/8/25 20:51
 **/
class OperationFactory{
    public static Operation createOperation(String operator) {
        Operation operation = null;
        switch (operator) {
            case "+":
                operation = new OperationAdd();
                break;
            case "-":
                operation = new OperationSub();
                break;
            case "*":
                operation = new OperationMul();
                break;
            case "/":
                operation = new OperationDiv();
                break;
            default:

        }
        return operation;
    }
 }
